import type { PiniaPluginContext } from 'pinia'
import { localCache } from './cache'
const KEYPREFIX = 'PINIA:STATE:'

/**
 * 状态仓库持久化插件
 */
function persistPlugin(context: PiniaPluginContext) {
  // 获取store对象
  const { store } = context
  // 定义存储状态的key，格式为KEYPREFIX + store的id
  const key = KEYPREFIX + store.$id
  //存储状态到localStorage中
  window.addEventListener('beforeunload', () => {
    localStorage.setItem(key, JSON.stringify(store.$state))
    // localCache.set(key, store.$state))
  })
  //取
  const item = localStorage.getItem(key)
  if (!item) return
  try {
    const originState = JSON.parse(item)
    store.$patch(originState)
  } catch (e) {
    throw new Error(`状态持久化失败,错误原因：${e}`)
  }
}

export default persistPlugin

//使用
// pinia.use(persistPlugin)
